import { Component, OnInit, ViewChild, Injector } from '@angular/core';
import { _HttpClient, SettingsService } from '@delon/theme';
import { SimpleTableComponent, SimpleTableColumn, SimpleTableButton } from '@delon/abc';
import { OrderService } from '../../../service/order/order.service';
import { CommService } from '../../../service/comm/comm.service';
import { EmitterService } from '../../../service/emit.service';
import { Router } from '@angular/router';
import { NzModalService } from 'ng-zorro-antd';
import { ServiceResult } from '@core/constant';
import { formatDate } from '@angular/common';
import { UserSelectModalComponent } from '@shared/component/users/user-select-modal.component';
import { SmsService } from '../../../service/sms/sms.service';
import { DeliveryViewModalComponent } from 'app/routes/warehouse/delivery-order/delivery-view/delivery-view.component';
import { BaseController } from '@shared/base-controller';

@Component({
  selector: 'warehouse-delivery-order',
  templateUrl: './delivery-order.component.html',
  styleUrls: ['./delivery-order.component.less']
})
export class WarehouseDeliveryOrderComponent extends BaseController implements OnInit {

  dateFormat = 'yyyy/MM/dd';
  ps = 10;
  q: any = {      
     deliveryId: '',
     dateRange: null     
  };  
  url = this.sms.queryDeliverys();
  data = [];
  checkedList = [];
  loading = false;
  
  types = [{text: '首批', value: 'P'}, {text: '定制', value: 'C'}, {text: '补货', value: 'B'}, {text: '安全补货', value: 'A'}];
  statuss = [{text: 'Pending', value: '0'}, {text: 'Shipping', value: '1'}, { text: 'Complete', value: '2'}, { text: 'Posting ', value: '3'}];  
  batchExportBtn = false;
  detailBtn = false;
  barcodeExportBtn = false;

  @ViewChild('st') st: SimpleTableComponent;
  columns: SimpleTableColumn[] = [];


  constructor(
    private orderServ: OrderService,
    private comm: CommService,
    public setting: SettingsService,
    private emit: EmitterService,
    private router: Router,
    private modalService: NzModalService,
    private sms: SmsService,
    public injector: Injector
  ) {
    super(injector);
  }

  ngOnInit() {
    this.batchExportBtn = this.getAuths("sms_delivery_batch_export");
    this.detailBtn = this.getAuths("sms_delivery_detail_btn");
    this.barcodeExportBtn = this.getAuths("sms_delivery_barcode_export");
    this.buildColumn();  
  }


  checkboxChange(list: any[]) {
    this.checkedList = list;
  }

  buildColumn() {
    this.columns = [
      { title: '', index: 'key', type: 'checkbox' },
      { title: '交货单', index: 'deliveryId', i18n: 'deliveryId' },
      { title: '发货日期', index: 'deliveryDate', i18n: 'shippingDate', type: 'date', dateFormat: 'YYYY/MM/DD' },
      { title: '客户', index: 'clientName', i18n: 'user', render: 'clientName' },     
      { title: '状态', index: 'status',  type: 'badge', i18n: 'status',
        filters: this.statuss,
        filterMultiple: false,
        filter: () => true,        
        filterConfirmText: 'Ok',
        filterClearText: 'Reset',
        badge: {
          '0': { text: 'Pending', color: 'error' },
          '1': { text: 'Shipping', color: 'processing' },
          '2': { text: 'Complete', color: 'warning'},
          '3': { text: 'Posting', color: 'success'}          
        }
      },      
      { title: '发货数量', index: 'qty', i18n: 'qty', className: 'text-center' },
      { title: '已发数量', index: 'sendQty', i18n: 'sendQty', className: 'text-center'  },
      { title: '未发数量', index: 'wf', i18n: 'wf', className: 'text-center' },                 
      { 
        title: '',
        buttons: [  
          { 
            text: "明细",
            i18n: 'view',
            type: 'modal',          
            component: DeliveryViewModalComponent,
            modal: {modalOptions: {nzStyle: {'top': '48px'}, nzBodyStyle: {'padding-top': '8px'}, nzTitle: 'Delivery Detail'}},
            paramName: 'record',   
            width: '1300px',                             
            click: (record: any, modal: any) => this.st.reload(),
            iif: (item: any, btn: SimpleTableButton, column: SimpleTableColumn) => {
              return this.detailBtn;
            }
          }, 
          {
            text: '导出条码',
            i18n: 'Expbars',
            type: 'none',
            click: ((record: any) => {
              this.sms.exportDeliveryBarcode(record.deliveryId);
            }),
            iif: (item: any, btn: SimpleTableButton, column: SimpleTableColumn) => {
              return this.barcodeExportBtn;
            }
          }                  
        ]
      }  
    ];
  }

  dateChange(result: Date[]): void {
    if (result.length != 0) {
      this.q.startDate = formatDate(result[0], 'yyyy-MM-dd', 'en-US');
      this.q.endDate = formatDate(result[1], 'yyyy-MM-dd', 'en-US');
    } else {
      this.q.startDate = '';
      this.q.endDate = '';
    }
  }


  showUserSelect() {
    let level = 'FIRST';
    if (this.setting.user.isManager) {
      level = 'FIRST';
    } else if (this.setting.user.level === 'FIRST') {
      level = 'SECOND';
    } else if (this.setting.user.level === 'SECOND') {
      level = 'THIRD';
    }
    const modal = this.modalService.create({
        nzContent: UserSelectModalComponent, 
        nzWidth: '730px', 
        nzComponentParams: { selectLevel: level, lockLevel: true, multi: false },                  
        nzFooter: null
    }); 
    modal.afterOpen.subscribe(() => {
        modal.getContentComponent().getSubject().subscribe(data => {
            let users = data as Array<any>; 
            if (users && users.length != 0) {
              this.q.agentCd = users[0].username;
            }                                                         
        })
    })
  }

  export() {
    if (this.checkedList.length > 0) {
      this.st.export(this.checkedList, { filename: 'agent_deliverys.xlsx' });
    } else {      
      let param = `?pageNumber=1&pageSize=0`;      
      if (this.st.extraParams.deliveryId) {
        param += "&deliveryId=" + this.st.extraParams.deliveryId;
      } 
      if (this.st.extraParams.agentCd) {
        param += "&agentCd=" + this.st.extraParams.agentCd;
      }
      if (this.st.extraParams.startDate) {
        param += "&startDate=" + this.st.extraParams.startDate;
      }
      if (this.st.extraParams.endDate) {
        param += "&endDate=" + this.st.extraParams.endDate;
      }
      if (this.st.extraParams.brand) {
        param += "&brand=" + this.st.extraParams.brand;
      }
      if (this.st.extraParams.status) {
        param += "&status=" + this.st.extraParams.status;
      }
      this.st.export(this.url + param, { filename: 'agent_deliverys.xlsx' });
    }
  }
}
